import random
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr

# 邮件服务器配置
SMTP_SERVER = "smtp.qq.com"  # QQ邮箱SMTP服务器
SMTP_PORT = 465  # QQ邮箱SSL端口
SMTP_USERNAME = "1820288492@qq.com"  # 替换为您的QQ邮箱
SMTP_PASSWORD = "xjlkdvsfualibdfa"  # 替换为您的QQ邮箱授权码
SENDER_EMAIL = "1820288492@qq.com"  # 替换为您的QQ邮箱


def generate_verification_code(length=6):
    """生成指定长度的数字验证码
    
    Args:
        length: 验证码长度，默认为6位
        
    Returns:
        str: 生成的验证码
    """
    return ''.join(random.choice('0123456789') for _ in range(length))


def send_verification_email(recipient_email, verification_code):
    """发送验证码邮件
    
    Args:
        recipient_email: 收件人邮箱
        verification_code: 验证码
        
    Returns:
        bool: 发送是否成功
    """
    try:
        # 创建邮件对象
        message = MIMEMultipart()
        from_header_name = Header('智能漏洞入侵检测系统', 'utf-8').encode()
        message['From'] = formataddr((from_header_name, SENDER_EMAIL))
        
        message['To'] = recipient_email
        message['Subject'] = Header('密码重置验证码', 'utf-8')
        
        # 邮件正文
        html_content = f"""
        <html>
        <body>
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;">
 
                <p>您好，</p>
                <p>您正在进行密码重置操作，您的验证码是：</p>
                <div style="background-color: #f5f5f5; padding: 10px; font-size: 24px; font-weight: bold; text-align: center; letter-spacing: 5px; margin: 20px 0;">
                    {verification_code}
                </div>
                <p>该验证码将在10分钟后失效，请尽快完成验证。</p>
                <p>如果您没有请求此验证码，请忽略此邮件。</p>

            </div>
        </body>
        </html>
        """
        message.attach(MIMEText(html_content, 'html', 'utf-8'))
        
        # 连接SMTP服务器并发送邮件
        try:
            server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, timeout=10)  # 设置10秒超时
            server.set_debuglevel(1)  # 启用调试模式
            server.login(SMTP_USERNAME, SMTP_PASSWORD)
            server.sendmail(SENDER_EMAIL, recipient_email, message.as_string())
            server.quit()
            return True
        except smtplib.SMTPAuthenticationError as e:
            print(f"SMTP认证失败: {str(e)}")
            return False
        except smtplib.SMTPException as e:
            print(f"SMTP错误: {str(e)}")
            return False
        except TimeoutError:
            print("SMTP服务器连接超时")
            return False
        except ConnectionError as e:
            print(f"连接错误: {str(e)}")
            return False
    except Exception as e:
        print(f"发送邮件失败: {str(e)}")
        return False